"""
用户实体模型
"""

from sqlalchemy import (
    Column, String, Text, Integer, Float, Boolean, 
    JSON, Enum as SQLEnum, Index, DateTime, ForeignKey
)
from sqlalchemy.orm import relationship, declarative_base
from datetime import datetime
from enum import Enum
import uuid

from ..core.database import Base


class UserRole(Enum):
    """用户角色"""
    ADMIN = "admin"
    USER = "user"
    GUEST = "guest"


class UserStatus(Enum):
    """用户状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    SUSPENDED = "suspended"
    BANNED = "banned"


class User(Base):
    """用户模型"""
    __tablename__ = "users"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    
    # 基本信息
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(100), unique=True, nullable=False, index=True)
    password_hash = Column(String(255), nullable=False)
    
    # 个人信息
    first_name = Column(String(50), nullable=True)
    last_name = Column(String(50), nullable=True)
    display_name = Column(String(100), nullable=True)
    avatar_url = Column(String(500), nullable=True)
    bio = Column(Text, nullable=True)
    
    # 状态和权限
    role = Column(SQLEnum(UserRole), default=UserRole.USER, index=True)
    status = Column(SQLEnum(UserStatus), default=UserStatus.ACTIVE, index=True)
    is_verified = Column(Boolean, default=False)          # 邮箱验证
    is_premium = Column(Boolean, default=False)           # 高级用户
    
    # 使用限制
    daily_quota = Column(Integer, default=100)            # 每日配额(分钟)
    monthly_quota = Column(Integer, default=3000)          # 每月配额(分钟)
    used_today = Column(Integer, default=0)                # 今日已用(分钟)
    used_month = Column(Integer, default=0)                # 本月已用(分钟)
    
    # 偏好设置
    language = Column(String(10), default="zh-CN")
    timezone = Column(String(50), default="Asia/Shanghai")
    theme = Column(String(20), default="light")            # light, dark
    
    # 隐私设置
    profile_public = Column(Boolean, default=False)
    activity_public = Column(Boolean, default=False)
    allow_analytics = Column(Boolean, default=True)
    
    # 元数据
    preferences = Column(JSON, nullable=True)               # 用户偏好
    settings = Column(JSON, nullable=True)                 # 应用设置
    extra_metadata = Column(JSON, nullable=True)           # 额外信息
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    last_login_at = Column(DateTime, nullable=True)
    last_activity_at = Column(DateTime, default=datetime.utcnow)
    
    # 统计信息
    login_count = Column(Integer, default=0)
    total_usage = Column(Float, default=0.0)               # 总使用时间(分钟)
    
    # 关系
    audiobooks = relationship("AudioBook", back_populates="user", cascade="all, delete-orphan")
    progress = relationship("AudioBookProgress", back_populates="user", cascade="all, delete-orphan")
    reviews = relationship("AudioBookReview", back_populates="user", cascade="all, delete-orphan")
    tags = relationship("AudioBookTag", back_populates="user", cascade="all, delete-orphan")
    voice_profiles = relationship("VoiceProfile", back_populates="user", cascade="all, delete-orphan")
    sessions = relationship("UserSession", back_populates="user", cascade="all, delete-orphan")
    api_keys = relationship("UserAPIKey", back_populates="user", cascade="all, delete-orphan")
    
    # 复合索引
    __table_args__ = (
        Index('idx_user_status_role', 'status', 'role'),
        Index('idx_user_created_at', 'created_at'),
    )
    
    def __repr__(self):
        return f"<User(id='{self.id}', username='{self.username}', email='{self.email}', role='{self.role.value}')>"
    
    def to_dict(self, include_sensitive=False):
        """转换为字典"""
        data = {
            "id": self.id,
            "username": self.username,
            "email": self.email if include_sensitive else None,
            "first_name": self.first_name,
            "last_name": self.last_name,
            "display_name": self.display_name,
            "avatar_url": self.avatar_url,
            "bio": self.bio,
            "role": self.role.value,
            "status": self.status.value,
            "is_verified": self.is_verified,
            "is_premium": self.is_premium,
            "daily_quota": self.daily_quota,
            "monthly_quota": self.monthly_quota,
            "used_today": self.used_today,
            "used_month": self.used_month,
            "language": self.language,
            "timezone": self.timezone,
            "theme": self.theme,
            "profile_public": self.profile_public,
            "activity_public": self.activity_public,
            "allow_analytics": self.allow_analytics,
            "preferences": self.preferences,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_login_at": self.last_login_at.isoformat() if self.last_login_at else None,
            "last_activity_at": self.last_activity_at.isoformat() if self.last_activity_at else None,
            "login_count": self.login_count,
            "total_usage": self.total_usage
        }
        
        if not include_sensitive:
            # 移除敏感信息
            data.pop("email", None)
        
        return data


class UserSession(Base):
    """用户会话模型"""
    __tablename__ = "user_sessions"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
    
    # 会话信息
    session_token = Column(String(255), unique=True, nullable=False, index=True)
    refresh_token = Column(String(255), unique=True, nullable=True, index=True)
    
    # 设备信息
    device_id = Column(String(100), nullable=True)
    device_type = Column(String(20), nullable=True)         # mobile, desktop, tablet
    device_name = Column(String(100), nullable=True)
    platform = Column(String(50), nullable=True)           # iOS, Android, Web, Desktop
    
    # 网络信息
    ip_address = Column(String(45), nullable=True)          # 支持IPv6
    user_agent = Column(Text, nullable=True)
    
    # 状态信息
    is_active = Column(Boolean, default=True)
    last_activity = Column(DateTime, default=datetime.utcnow)
    expires_at = Column(DateTime, nullable=False)
    
    # 位置信息
    country = Column(String(2), nullable=True)
    region = Column(String(50), nullable=True)
    city = Column(String(50), nullable=True)
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # 关系
    user = relationship("User", back_populates="sessions")
    
    def __repr__(self):
        return f"<UserSession(id='{self.id}', user_id='{self.user_id}', active={self.is_active})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "device_type": self.device_type,
            "device_name": self.device_name,
            "platform": self.platform,
            "is_active": self.is_active,
            "last_activity": self.last_activity.isoformat() if self.last_activity else None,
            "expires_at": self.expires_at.isoformat() if self.expires_at else None,
            "country": self.country,
            "region": self.region,
            "city": self.city,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }


class UserAPIKey(Base):
    """用户API密钥模型"""
    __tablename__ = "user_api_keys"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
    
    # 密钥信息
    name = Column(String(100), nullable=False)              # 密钥名称
    key_hash = Column(String(255), nullable=False)         # 密钥哈希
    key_prefix = Column(String(10), nullable=False)        # 密钥前缀(用于显示)
    
    # 权限信息
    permissions = Column(JSON, nullable=False)             # 权限列表
    rate_limit = Column(Integer, default=1000)              # 每小时请求限制
    allowed_ips = Column(JSON, nullable=True)               # 允许的IP列表
    
    # 使用限制
    daily_limit = Column(Integer, default=10000)            # 每日请求限制
    used_today = Column(Integer, default=0)                  # 今日使用次数
    
    # 状态信息
    is_active = Column(Boolean, default=True)
    is_expired = Column(Boolean, default=False)
    
    # 时间信息
    expires_at = Column(DateTime, nullable=True)             # 过期时间
    last_used_at = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # 关系
    user = relationship("User", back_populates="api_keys")
    
    def __repr__(self):
        return f"<UserAPIKey(id='{self.id}', user_id='{self.user_id}', name='{self.name}')>"
    
    def to_dict(self, include_key=False):
        """转换为字典"""
        data = {
            "id": self.id,
            "user_id": self.user_id,
            "name": self.name,
            "key_prefix": self.key_prefix,
            "permissions": self.permissions,
            "rate_limit": self.rate_limit,
            "allowed_ips": self.allowed_ips,
            "daily_limit": self.daily_limit,
            "used_today": self.used_today,
            "is_active": self.is_active,
            "is_expired": self.is_expired,
            "expires_at": self.expires_at.isoformat() if self.expires_at else None,
            "last_used_at": self.last_used_at.isoformat() if self.last_used_at else None,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_key:
            data["api_key"] = self.get_full_key()
        
        return data
    
    def get_full_key(self):
        """获取完整密钥(仅用于创建时)"""
        # 这里应该是从安全存储中获取实际密钥
        return None


class UserActivity(Base):
    """用户活动日志模型"""
    __tablename__ = "user_activities"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
    
    # 活动信息
    activity_type = Column(String(50), nullable=False, index=True)  # login, logout, play, create等
    resource_type = Column(String(50), nullable=True)               # audiobook, voice_profile等
    resource_id = Column(String, nullable=True)                     # 资源ID
    
    # 活动详情
    title = Column(String(200), nullable=True)
    description = Column(Text, nullable=True)
    extra_metadata = Column(JSON, nullable=True)
    
    # 设备和位置信息
    ip_address = Column(String(45), nullable=True)
    user_agent = Column(Text, nullable=True)
    device_id = Column(String(100), nullable=True)
    
    # 时间戳
    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<UserActivity(id='{self.id}', user_id='{self.user_id}', type='{self.activity_type}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "activity_type": self.activity_type,
            "resource_type": self.resource_type,
            "resource_id": self.resource_id,
            "title": self.title,
            "description": self.description,
            "metadata": self.metadata,
            "ip_address": self.ip_address,
            "user_agent": self.user_agent,
            "device_id": self.device_id,
            "timestamp": self.timestamp.isoformat() if self.timestamp else None
        }


class UserSettings(Base):
    """用户设置模型"""
    __tablename__ = "user_settings"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String, ForeignKey("users.id"), nullable=False, unique=True, index=True)
    
    # 音频设置
    default_voice_id = Column(String, nullable=True)
    default_voice_preset = Column(String, nullable=True)
    default_audio_format = Column(String(10), default="mp3")
    default_sample_rate = Column(Integer, default=22050)
    default_bitrate = Column(Integer, default=128)
    
    # 播放设置
    auto_play = Column(Boolean, default=True)
    remember_position = Column(Boolean, default=True)
    playback_speed = Column(Float, default=1.0)
    volume = Column(Float, default=1.0)
    
    # 界面设置
    items_per_page = Column(Integer, default=20)
    show_thumbnails = Column(Boolean, default=True)
    compact_view = Column(Boolean, default=False)
    
    # 通知设置
    email_notifications = Column(Boolean, default=True)
    push_notifications = Column(Boolean, default=False)
    processing_complete = Column(Boolean, default=True)
    
    # 高级设置
    cache_enabled = Column(Boolean, default=True)
    cache_size = Column(Integer, default=1000)             # MB
    quality_preference = Column(String(20), default="balanced")  # low, balanced, high
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f"<UserSettings(id='{self.id}', user_id='{self.user_id}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "default_voice_id": self.default_voice_id,
            "default_voice_preset": self.default_voice_preset,
            "default_audio_format": self.default_audio_format,
            "default_sample_rate": self.default_sample_rate,
            "default_bitrate": self.default_bitrate,
            "auto_play": self.auto_play,
            "remember_position": self.remember_position,
            "playback_speed": self.playback_speed,
            "volume": self.volume,
            "items_per_page": self.items_per_page,
            "show_thumbnails": self.show_thumbnails,
            "compact_view": self.compact_view,
            "email_notifications": self.email_notifications,
            "push_notifications": self.push_notifications,
            "processing_complete": self.processing_complete,
            "cache_enabled": self.cache_enabled,
            "cache_size": self.cache_size,
            "quality_preference": self.quality_preference,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }
